<script setup lang="ts">
import { useInterval, useMouse, useOnline, usePageLeave, useTitle, useDebounce, useThrottle, useGeolocation, useIntersectionObserver } from '@vueuse/core'
import { ref, watch, computed, shallowRef, useTemplateRef } from 'vue'
// 引入Element Plus组件
import { ElMessage } from 'element-plus'

const msgCount = ref(3)
const keyword = ref('')
const ripples = ref<Array<{ id: number, x: number, y: number }>>([])
let rippleId = 0

useTitle(() => msgCount.value ? `(${msgCount.value}) 条新消息 - 我的站点` : '我的站点')
const { counter, pause, resume } = useInterval(1000, { controls: true })
const currentTime = ref(new Date().toLocaleString());
setInterval(() => {
  currentTime.value = new Date().toLocaleString();
}, 1000)
const { x, y } = useMouse()
const online = useOnline()
const isLeave = usePageLeave()
const debounced = useDebounce(keyword, 500)
const throttledX = useThrottle(x, 1000)
const throttledY = useThrottle(y, 1000)
const { coords, isSupported, locatedAt, error } = useGeolocation()
const lat = computed(() => coords.value?.latitude)
const lng = computed(() => coords.value?.longitude)

watch(debounced, () => {
  ElMessage.info(`搜索关键词：${debounced.value}`)
})

// 消息已读处理函数
const handleReadMessage = () => {
  if (msgCount.value > 0) {
    msgCount.value--
    ElMessage.success('已标记为已读')
  } else {
    ElMessage.warning('没有未读消息')
  }
}

// 处理鼠标点击，创建水波纹
const handleClick = (event: MouseEvent) => {
  const rect = event.currentTarget as HTMLElement
  const rectBounds = rect.getBoundingClientRect()
  const x = event.clientX - rectBounds.left
  const y = event.clientY - rectBounds.top

  // 添加新的水波纹
  const id = rippleId++
  ripples.value.push({ id, x, y })

  // 动画结束后移除水波纹
  setTimeout(() => {
    ripples.value = ripples.value.filter(ripple => ripple.id !== id)
  }, 1000)
}
const main = useTemplateRef<HTMLDivElement>('main')
const mainIsVisible = shallowRef(false)
const { stop } = useIntersectionObserver(main, entries => {
  entries.forEach(entry => {
    mainIsVisible.value = entry?.isIntersecting || false
    if (entry.isIntersecting) {
      console.log('元素进入视口')
      // 停止观察，防止重复触发
      stop();
    }
  }, { threshold: 0.5 }) // 50% visible
})
const { } = useIntersectionObserver(
  main,
  ([entry]) => {
    mainIsVisible.value = entry?.isIntersecting || false
  }, { threshold: 0.5 }
)
const { } = useIntersectionObserver(
  main,
  ([{ isIntersecting }]) => {
    mainIsVisible.value = isIntersecting
  }, { threshold: 0.5 }
)
</script>
<template>
  <div ref="main" class="p-10 overflow-hidden relative h-[100vh]" @click="handleClick">
    <!-- 水波纹容器 -->
    <div v-for="ripple in ripples" :key="ripple.id" class="ripple border"
      :style="{ left: ripple.x + 'px', top: ripple.y + 'px' }" />

    <p>当前鼠标位置：{{ x }}, {{ y }}</p>
    <p>鼠标 X 每 1 秒更新一次：{{ throttledX }}</p>
    <p>鼠标 Y 每 1 秒更新一次：{{ throttledY }}</p>
    <p>距网页加载成功已过去 {{ counter }} 秒</p>
    <el-button type="primary" @click.stop="pause" class="mr-2">暂停</el-button>
    <el-button type="success" @click.stop="resume" class="mr-2">继续</el-button>

    <div class="ball" :style="{ left: x + 'px', top: y + 'px' }" />

    <div v-if="!online" class="tip">网络已断开，请检查连接</div>

    <!-- <div v-if="isLeave" class="mask">
      <div class="dialog">别走！送你 10 元券~<button @click="isLeave = false">关闭</button></div>
    </div> -->

    <el-button type="info" @click.stop="handleReadMessage" class="mr-2">
      已读一条 <el-badge :value="msgCount" v-if="msgCount > 0" />
    </el-button>

    <el-input v-model="keyword" placeholder="输入关键词" class="mt-0" style="width: 300px;" clearable />

    <div>
      <p>当前时间：{{ currentTime }}</p>
      <p>当前定位时间：{{ locatedAt ? new Date(locatedAt).toLocaleString() : 'N/A' }}</p>
    </div>
    <div>
      <button v-if="!isSupported" disabled>正在定位…</button>
      <div v-else-if="error">定位失败：{{ error.message }}</div>
      <div v-else>您当前位置：{{ lat.toFixed(6) }}, {{ lng.toFixed(6) }}</div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.ball {
  position: fixed;
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
  pointer-events: none;
  transform: translate(-50%, -50%);
}

.tip {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffeb3b;
  text-align: center;
  padding: 6px;
}

.mask {
  position: fixed;
  inset: 0;
  background: #0006;
  display: flex;
  align-items: center;
  justify-content: center;

  .dialog {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
  }
}

/* 水波纹样式 */
.ripple {
  position: absolute;
  border-radius: 50%;
  background-color: rgba(255, 255, 0, 0.8);
  border: solid 1px #ff0;
  transform: translate(-50%, -50%);
  animation: ripple-effect 1s ease-out forwards;
  pointer-events: none;
  z-index: 9999;
  user-select: none;
}

/* 水波纹动画 */
@keyframes ripple-effect {
  0% {
    width: 0;
    height: 0;
    opacity: 0.8;
  }

  100% {
    width: 100px;
    height: 100px;
    opacity: 0;
  }
}

/* 隐藏鼠标指针 */
.p-10 {
  cursor: none;
}
</style>